<template>
  <div class="dingtalk-auto-login">
    <van-loading v-if="loading" vertical class="loading">
      自动登录中...
    </van-loading>

    <div v-else class="error-container">
      <van-empty image="error" :description="errorMessage" />
      <van-button type="primary" size="small" @click="handleRetry">
        重试
      </van-button>
    </div>
  </div>
</template>
  
  <script setup>
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import axios from "axios";
import ddAuthConfig from "@/utils/ddAuthConfig";
import { useUserStore } from "@/stores/userInfo";
const userStore = useUserStore();
import { removeToken, setToken } from "@/utils/auth";

const router = useRouter();
const loading = ref(true);
const errorMessage = ref("");

// 环境检测-是否是钉钉环境
const isDingTalkEnv = () => {
  return (
    typeof window.dd !== "undefined" &&
    window.dd.env &&
    window.dd.env.platform !== "notInDingTalk"
  );
};
// 获取钉钉授权码
const getAuthCode = (corpId) => {
  return new Promise((resolve, reject) => {
    window.dd.ready(() => {
      window.dd.runtime.permission.requestAuthCode({
        corpId: corpId,
        onSuccess: (res) => resolve(res.code),
        onFail: (err) =>
          reject(new Error(err.errorMessage || "获取授权码失败")),
      });
    });

    window.dd.error((err) => {
      reject(new Error("钉钉SDK初始化失败"));
    });
  });
};

// const getDingToken = () => {
//   return new Promise((resolve, reject) => {
//     axios
//       .get(
//         `/dingtalk-proxy/gettoken?appkey=${ddAuthConfig.appkey}&appsecret=${ddAuthConfig.appsecret}`
//       )
//       .then((response) => {
//         const res = response.data || {};
//         if (res.errcode === 0) {
//           resolve(res.access_token);
//         } else {
//           reject(res.errmsg);
//           showFailToast("获取钉钉access_token失败");
//         }
//       })
//       .catch((error) => {
//         reject("获取钉钉access_token失败");
//         showFailToast("获取钉钉access_token失败");
//       });
//   });
// };

// 用户信息返回示例：
// {
// "code": "200",
// "data": {
//     "errcode": 0,
//     "errmsg": "ok",
//     "result": {
//         "device_id": "28941cd070d99fe08e38ca14da098870",
//         "name": "Seaboy Ye/叶海波",
//         "sys": false,
//         "sys_level": 0,
//         "unionid": "jiSPIwgUbM7KtIAD22iivnowiEiE",
//         "userid": "11158612"
//     },
//     "request_id": "15rmjdz7qrhua"
// }
// }
const getUserInfo = (code) => {
  return new Promise((resolve, reject) => {
    removeToken()
    //获取token
    axios
      .post(`${import.meta.env.VITE_API_JAVA_ROOT}/relate/login`, {
        userName: "relate",
        password: "relate",
      })
      .then((response) => {
        const res = response.data || {};
        if (res.code === 200 && res.result) {
          const token = res.result.token || "";
          setToken(token);
          //钉钉自动登录
          axios
            .get(
              `${
                import.meta.env.VITE_API_JAVA_ROOT
              }/relate/authLogin?code=${code}`,
              {
                headers: {
                  Token: token,
                },
              }
            )
            .then((response) => {
              if (response.status === 200) {
                const res = response.data || {};
                if (res.code === 200) {
                  const loginData = JSON.parse(res.result) || {};
                  if (loginData.errcode === 0) {
                    resolve(loginData.result);
                  } else {
                    loginData.errmsg && reject(new Error(loginData.errmsg));
                  }
                } else {
                  res.message && reject(new Error(res.message));
                }
              } else {
                response.statusText && reject(new Error(response.statusText));
              }
            })
            .catch((error) => {
              reject(new Error(error.message || "获取钉钉用户信息失败"));
            });
        } else {
          reject(new Error(res.message));
        }
      })
      .catch((error) => {
        reject(new Error(error.message || "获取钉钉登录token失败"));
      });
  });
};

// 执行登录流程
const handleLogin = async () => {
  try {
    if (!isDingTalkEnv()) {
      throw new Error("请使用钉钉客户端打开");
    }
    // const authCode = "cfe9513981003da5bc9a15208d282e7f";
    //获取钉钉授权码
    const authCode = await getAuthCode(ddAuthConfig.corpId);
    const userInfo = await getUserInfo(authCode);
    userStore.setUserInfo(userInfo); //用户信息
    router.replace("/");
  } catch (error) {
    errorMessage.value = error.message;
    loading.value = false;
    showFailToast(error.message);
  }
};

// 重试处理
const handleRetry = () => {
  loading.value = true;
  errorMessage.value = "";
  handleLogin();
};

onMounted(() => {
  handleLogin();
});
</script>
  
  <style scoped>
.dingtalk-auto-login {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.loading {
  padding: 16px;
  border-radius: 8px;
}

.error-container {
  text-align: center;
  padding: 20px;
}
</style>